<!-- 选择对账单弹窗 -->
<template>
  <el-dialog
    v-model="dialogFormVisible"
    title="选择对账单"
    width="70%"
    draggable
    overflow
    @close="handleClose"
  >
    <div class="crossRope" />
    <el-form style="margin-top: 2%">
      <vxe-table
        ref="xTable"
        border
        min-height="350"
        max-height="550"
        header-align="center"
        :column-config="{ resizable: true }"
        :row-config="{ isHover: true }"
        :data="tableData"
        size="mini"
        :loading="tableLoading"
        :pager-config="tablePage"
      >
        <vxe-column type="checkbox" width="60" align="center" />
        <vxe-column
          v-for="column in tableColumns"
          :key="column.field"
          :field="column.field"
          :title="column.title"
          :min-width="column.width"
          :align="column.align"
          header-align="center"
          show-overflow
        >
          <template
            v-if="column.field === 'reconciliationDate'"
            v-slot:default="{ row }"
          >
            {{ row.reconciliationStartDate + "至" + row.reconciliationEndDate }}
          </template>
          <template v-else v-slot:default="{ row }">
            {{ row[column.field] }}
          </template>
        </vxe-column>
        <vxe-column title="操作" min-width="100" align="center" fixed="right">
          <template v-slot:default="{ row }">
            <vxe-button
              type="text"
              size="small"
              @click="
                toDetail(
                  { id: row.id, title: row.contractName, action: 'view' },
                  'viewReconcoilation'
                )
              "
              >查看</vxe-button
            >
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager
        v-model:current-page="tablePage.currentPage"
        v-model:page-size="tablePage.pageSize"
        :layouts="[
          'Sizes',
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'FullJump',
          'Total'
        ]"
        :total="tablePage.total"
        size="mini"
        style="margin-top: 2%"
        @page-change="handlePageChange"
      />
    </el-form>
    <div class="crossRope" />
    <div style="text-align: right; margin-top: 2%">
      <el-button
        color="#1E3485"
        :icon="Select"
        size="small"
        @click="selectConfirm"
        >确定</el-button
      >
      <el-button :icon="CloseBold" size="small" @click="handleClose"
        >关闭</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElDialog, ElMessage } from "element-plus";
import { Select, CloseBold } from "@element-plus/icons-vue";
import { VxePagerEvents, VxeTable } from "vxe-table";
import { useDetail } from "@/views/ERP_settlement/hooks";
import { getReconciliationDataList } from "@/api/ERP_settlement";

const { toDetail, router } = useDetail();
// 弹窗关闭/打开
const props = defineProps({
  visible: Boolean,
  contractId: String
});
const dialogFormVisible = ref(false);
const emit = defineEmits(["close", "confirm"]);
function handleClose() {
  emit("close", false);
}
watch(
  () => props.visible,
  val => {
    dialogFormVisible.value = val;
  },
  { immediate: true }
);

// 表格配置
let tableLoading = ref(false);
let tableData = ref([]);
let xTable = ref(null);
const selectedRow = ref(null as any);
const tableColumns = reactive([
  {
    field: "reconciliationDate",
    title: "对账周期",
    width: 150,
    align: "center"
  },
  {
    field: "supplyNum",
    title: "供货清单",
    width: 150,
    align: "center"
  },
  {
    field: "supplyIncludingTaxTotalPrice",
    title: "含税总价（元）",
    width: 150,
    align: "right"
  },
  {
    field: "ycConfirmDate",
    title: "对账完成时间",
    width: 150,
    align: "center"
  }
]);
// 表格分页配置
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};
// 获取表格数据
async function getList() {
  tableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  params.contractId = props.contractId;
  params.status = 7; // 云采确认完成
  try {
    const response: ApiResponse = await getReconciliationDataList(params);
    tableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  } catch (error) {
    ElMessage.error("获取表格数据失败");
  } finally {
    tableLoading.value = false;
  }
}
// 获取选中行
function getSelectedRows() {
  return xTable.value.getCheckboxRecords();
}
// 确认事件
function selectConfirm() {
  if (getSelectedRows().length === 0) {
    ElMessage.error("请选择一条数据");
  } else {
    let dataList = [];
    for (let i = 0; i < getSelectedRows().length; i++) {
      dataList.push({
        id: getSelectedRows()[i].id,
        contractName: getSelectedRows()[i].contractName,
        reconciliationStartDate: getSelectedRows()[i].reconciliationStartDate,
        reconciliationEndDate: getSelectedRows()[i].reconciliationEndDate,
        supplyNum: getSelectedRows()[i].supplyNum,
        supplyIncludingTaxTotalPrice:
          getSelectedRows()[i].supplyIncludingTaxTotalPrice,
        reconciliationPrice: getSelectedRows()[i].reconciliationPrice,
        reconciliationConfirmDate:
          getSelectedRows()[i].reconciliationConfirmDate
      });
    }
    emit("confirm", {
      dataList: dataList
    });
    // 关闭弹窗
    handleClose();
  }
}
// 打开弹窗时执行
watch(dialogFormVisible, newValue => {
  if (newValue) {
    getList();
  }
});
</script>
